package com.yanqu.road.server.manager.activity.commonteam;

import com.yanqu.road.entity.activity.commonteam.CommonTeamConfigData;
import com.yanqu.road.entity.activity.commonteam.data.CommonTeamApplyData;
import com.yanqu.road.entity.activity.commonteam.data.CommonTeamData;
import com.yanqu.road.entity.activity.commonteam.data.CommonTeamUserData;
import com.yanqu.road.entity.activity.commonteam.enums.CommonTeamLogMemberOpType;
import com.yanqu.road.entity.log.cross.commonteam.LogCrossCommonTeamMemberOp;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.CommonTeamProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.log.CrossAutoLogMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.utils.FixSizeLinkedList;
import com.yanqu.road.utils.YanQuMessageUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通用队伍对象
 */
public class CommonTeam extends CommonTeamData {

    /**
     * 成员数据
     */
    private Map<Long, CommonTeamUserData> memberDataMap = new ConcurrentHashMap<Long, CommonTeamUserData>();

    /**
     * 申请入队数据
     */
    private Map<Long, CommonTeamApplyData> applyDataMap = new ConcurrentHashMap<>();

    /**
     * 删除的入队数据
     */
    private Map<Long, CommonTeamApplyData> delApplyDataMap = new ConcurrentHashMap<>();

    /**
     * 队伍聊天信息，30条
     */
    private FixSizeLinkedList<CommonTeamProto.CommonTeamChatMsg> chatMsgList = new FixSizeLinkedList<>(30);

    public CommonTeam() {}

    public CommonTeam(CommonTeamData commonTeamData) {
        super(commonTeamData);
    }

    public CommonTeam(int activityId, int groupId, long serverId, int teamId, String teamName, long leaderId, String leaderName, long score) {
        super(activityId, groupId, serverId, teamId, teamName, leaderId, leaderName, score);
    }

    public void setMemberDataMap(Map<Long, CommonTeamUserData> memberDataMap) {
        this.memberDataMap = memberDataMap;
    }

    public void setApplyDataMap(Map<Long, CommonTeamApplyData> applyDataMap) {
        this.applyDataMap = applyDataMap;
    }

    /**
     * 注入成员
     * @param data
     */
    public void addMemberData(CommonTeamUserData data) {
        data.setTeamId(this.getTeamId());
        data.setLastJoinTeamTime(System.currentTimeMillis());
        memberDataMap.put(data.getUserId(), data);
    }

    /**
     * 移除成员
     * @param data
     */
    public void removeMemberData(CommonTeamUserData data) {
        data.setTeamId(0);
        memberDataMap.remove(data.getUserId());
    }

    /**
     * 获取成员MAP
     * @return
     */
    public Map<Long, CommonTeamUserData> getMemberDataMap() {
        return memberDataMap;
    }

    /**
     * 获取成员
     * @param userId
     * @return
     */
    public CommonTeamUserData getMemberData(long userId) {
        return memberDataMap.get(userId);
    }

    /**
     * 获取申请数据MAP
     * @return
     */
    public Map<Long, CommonTeamApplyData> getApplyDataMap() {
        return applyDataMap;
    }

    /**
     * 获取被删除的申请数据
     * @return
     */
    public Map<Long, CommonTeamApplyData> getDelApplyDataMap() {
        return delApplyDataMap;
    }

    /**
     * 清除被删除的申请数据
     */
    public void clearDelApplyDataMap() {
        this.delApplyDataMap.clear();
    }

    /**
     * 注入申请数据
     * @param data
     */
    public void putApplyData(CommonTeamApplyData data) {
        applyDataMap.put(data.getUserId(), data);
    }

    /**
     * 撤销申请数据
     * @param userId
     */
    public synchronized void removeApplyData(long userId) {
        CommonTeamApplyData applyData = applyDataMap.remove(userId);
        if (applyData != null) {
            applyData.setDelFlag(1);
            this.delApplyDataMap.put(applyData.getUserId(), applyData);
            //日志
            LogCrossCommonTeamMemberOp log = new LogCrossCommonTeamMemberOp(
                    this.getActivityId(),
                    this.getGroupId(),
                    userId,
                    this.getTeamId(),
                    CommonTeamLogMemberOpType.CANCEL_APPLY.getType()
            );
            CrossAutoLogMgr.add(log);
        }
    }

    /**
     * 获取玩家的申请数据
     * @param userId
     * @return
     */
    public CommonTeamApplyData getApplyData(long userId) {
        return applyDataMap.get(userId);
    }

    /**
     * 判断玩家是否在申请列表
     * @param userId
     * @return
     */
    public boolean checkInApply(long userId) {
        return this.getApplyData(userId) != null;
    }

    public synchronized void addApplyData(CommonTeamUserData userData, CommonTeamConfigData teamConfig) {
        //添加申请
        CommonTeamApplyData applyData = new CommonTeamApplyData(
                teamConfig.getActivityId(),
                this.getGroupId(),
                userData.getUserId(),
                userData.getUserName(),
                userData.getServerId(),
                this.getTeamId(),
                userData.getScore()
        );
        this.putApplyData(applyData);
        //日志
        LogCrossCommonTeamMemberOp log = new LogCrossCommonTeamMemberOp(
                this.getActivityId(),
                this.getGroupId(),
                userData.getUserId(),
                this.getTeamId(),
                CommonTeamLogMemberOpType.APPLY.getType()
        );
        CrossAutoLogMgr.add(log);

    }

    /**
     * 退出队伍
     * @param data
     */
    public void quitTeam(CommonTeamUserData data) {
        this.removeMemberData(data);
    }

    /**
     * 一键拒绝入队
     */
    public void oneKeyRejectJoinTeam() {
        Iterator<Map.Entry<Long, CommonTeamApplyData>> iterator = this.applyDataMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, CommonTeamApplyData> entry = iterator.next();
            CommonTeamApplyData applyData = entry.getValue();
            this.removeApplyData(applyData.getUserId());
        }
    }

    /**
     * 获取队长信息
     * @return
     */
    public CommonTeamUserData getLeaderUserData() {
        return this.getMemberDataMap().get(this.getLeaderId());
    }

    /**
     * 获取队伍总实力
     * @return
     */
    public long getTeamPower() {
        return this.getMemberDataMap().values().stream().mapToLong(CommonTeamUserData::getScore).sum();
    }

    /**
     * 获取聊天信息LIST
     * @return
     */
    public FixSizeLinkedList<CommonTeamProto.CommonTeamChatMsg> getTeamChatMsgList() {
        //格式化聊天消息
        return CommonTeamMgr.formatTeamChatMsgList(this.getActivityId(), this.getGroupId(), this.chatMsgList);
    }

    /**
     * 同步队友聊天信息
     * @param chatMsg
     */
    public synchronized void sendTeamChatMsg(CommonTeamProto.CommonTeamChatMsg chatMsg) {
        //添加队伍聊天信息
        this.chatMsgList.add(chatMsg);
        //同步队伍聊天消息
        for (CommonTeamUserData member : this.memberDataMap.values()) {
            this.sendTeamMemberChatMsg(member, chatMsg);
        }
    }

    /**
     * 同步队友聊天信息
     * @param member
     * @param chatMsg
     */
    private void sendTeamMemberChatMsg(CommonTeamUserData member, CommonTeamProto.CommonTeamChatMsg chatMsg) {
        CommonTeamProto.CommonTeamSyncChatMsg.Builder builder = CommonTeamProto.CommonTeamSyncChatMsg.newBuilder();
        builder.setActivityId(this.getActivityId());
        builder.setMsg(chatMsg);
        YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_COMMON_TEAM_SYNC_CHAT_MSG, builder);
        MessageHelper.sendPacket(member.getServerId(), member.getUserId(), message);
    }
}
